package tgc.edu.tgq.bootstrap.web.controller;



import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.tgq.bootstrap.custom.AjaxResult;
import tgc.edu.tgq.bootstrap.custom.BaseController;
import tgc.edu.tgq.bootstrap.entity.Teacher;
import tgc.edu.tgq.bootstrap.service.TeacherService;
import tgc.edu.tgq.bootstrap.web.form.StudentForm;
import tgc.edu.tgq.bootstrap.web.form.TeacherFrom;


@Controller
@RequestMapping(value = "/teacher")
public class TeacherController extends BaseController<Teacher, Integer, TeacherFrom>{
	@Autowired
	private TeacherService service;
	@RequestMapping(value = "/pwd")
	public void pwd(ModelMap modelMap) {
		
	}
	@Override
	public Specification<Teacher> buildSpec(TeacherFrom form) {
		@SuppressWarnings("serial")
		Specification<Teacher> spec=new Specification<Teacher>() {

			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String username = form.getUsername();
				if(StringUtils.hasText(username)) {
					rules.add(cb.like(root.get("username"), "%"+username+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(TeacherFrom form) {

		Boolean flag = service.save(form);
		if(flag) {
			return new AjaxResult("数据保存成功");
		}
		return new AjaxResult(false, "数据保存失败");
	}
	@RequestMapping(value ="/resetPwd")
	@ResponseBody
	public Object resetPwd(StudentForm form) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		Integer id = form.getId();
		Teacher teacher =service.findById(id);
		teacher.setPassword(encoder.encode("1111"));
		service.save(teacher);
		return new AjaxResult("密码重置成功");
	}
}
